package cn.cytong.nk0713.utils.nutz;

import org.nutz.dao.Sqls;
import org.nutz.dao.impl.NutDao;
import org.nutz.dao.sql.Sql;
import org.nutz.lang.Stopwatch;

/**
 * 用于执行批处理的sql对象
 */
public class BatchSql {
    private String sqlSource;
    private Sql sql;
    private int batchSize = 0;

    public BatchSql(String sqlSource) {
        this.sqlSource = sqlSource;
        sql = Sqls.create(SqlUtility.replaceParamNames(sqlSource));
    }

    public void addBatch(Object... params) {
        for (int i = 0; i < params.length; i++) {
            sql.params().set("p" + i, params[i]);
        }
        sql.addBatch();
        batchSize++;
    }

    public void clearBatch() {
        sql.clearBatch();
    }

    public int getBatchSize() {
        return batchSize;
    }

    public Sql getSql() {
        return sql;
    }

    /**
     * 执行批处理
     *
     * @param dao
     */
    public void execute(NutDao dao) {
        if (batchSize > 0) {
            Stopwatch sw = Stopwatch.begin();
            dao.execute(sql);
            sw.stop();
            sql.clearBatch();
        }
    }

}
